package com.blb.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.blb.entity.Menu;
import com.blb.entity.Role;
import com.blb.entity.User;
import com.blb.entity.UserExample;
import com.blb.entity.UserExample.Criteria;
import com.blb.entity.Userrole;
import com.blb.entity.UserroleExample;
import com.blb.mapper.MenuExtMapper;
import com.blb.mapper.RoleMapper;
import com.blb.mapper.UserMapper;
import com.blb.mapper.UserroleMapper;
import com.blb.service.IUserService;
import com.blb.utils.LayuiPage;
import com.blb.utils.PasswordHelp;
import com.blb.utils.SessionUtils;
import com.blb.utils.UUIDUtils;
import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("user")
public class UserController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private MenuExtMapper menuExtMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private UserroleMapper userroleMapper;
	
	/**
	 * 跳转用户管理界面
	 * @param menuId
	 * @return
	 * @throws IOException 
	 */
	@RequiresPermissions("user:list")
	@RequestMapping("showList")
	public String showList(String menuId, Model model) throws IOException{
		//查询当前用户拥有哪些按钮
		List<Menu> list = menuExtMapper.getButtonByUserId(SessionUtils.getUserId(), menuId);
		model.addAttribute("bts", list);
		return "user/user_list";
	}

	/**
	 * 分页
	 * @param page
	 * @param limit
	 * @param username
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("page")
	public LayuiPage PageData(int page, int limit, String username) throws IOException{
		List<User> list = userMapper.page((page-1)*limit, limit, username);
		
		UserExample userExample = new UserExample();
		if (!StringUtils.isNullOrEmpty(username)) {
			Criteria criteria = userExample.createCriteria();
			criteria.andUsernameLike("%"+username+"%");
		}
		int count = (int) userMapper.countByExample(userExample);
		LayuiPage layuiPage = new LayuiPage();
		layuiPage.setData(list);
		layuiPage.setCount(count);
		return layuiPage;
	}
	
	/**
	 * 显示添加页面
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("showAdd")
	public String showAdd(Model model) throws IOException{
		//查询所有角色，并放入request作用域中，在user_add.jsp中取出来
		List<Role> list = roleMapper.selectByExample(null);
		model.addAttribute("roles", list);
		return "user/user_add";
	}
	
	/**
	 * 添加
	 * @param user
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("add")
	public String add(User user, @Param("roles")String roles) {
		try {
			PasswordHelp.getNewPassword(user);
			user.setId(UUIDUtils.getID());
			user.setCreateTime(new Date());
			user.setCreateUser(SessionUtils.getUserName());
			userService.add(user, roles);
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return "";
	}
	
	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("delete")
	public String delete(@RequestBody List<String> ids){
		UserExample userExample = new UserExample();
		userExample.createCriteria().andIdIn(ids);
		userMapper.deleteByExample(userExample);
		
		//删除用户角色关联表信息
		UserroleExample userroleExample = new UserroleExample();
		userroleExample.createCriteria().andUserIdIn(ids);
		userroleMapper.deleteByExample(userroleExample);
		
		return "";
	}
	
	/**
	 * 判断用户名是否存在
	 * @param username
	 * @return
	 */
	@ResponseBody
	@RequestMapping("isExist")
	public String isExist(String username){
		UserExample userExample = new UserExample();
		userExample.createCriteria().andUsernameEqualTo(username);
		List<User> list = userMapper.selectByExample(userExample);
		if (!list.isEmpty()) {
			return "用户名已存在";
		}
		return "";
	}
	
	/**
	 * 跳转修改界面
	 * @param user
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("showUpdate")
	public String showUpdate(User user, Model model) throws IOException{
		
		//查询所有角色
		List<Role> list = roleMapper.selectByExample(null);
		
		//已选择角色
		UserroleExample userroleExample = new UserroleExample();
		userroleExample.createCriteria().andUserIdEqualTo(user.getId());
		List<Userrole> list2 = userroleMapper.selectByExample(userroleExample);
		
		//将已选择角色的集合转成json字符串，然后再传递到jsp页面
		String choiseRoles = "";
		if (!list2.isEmpty()) {
			choiseRoles = JSON.toJSON(list2).toString();
		}
		model.addAttribute("roles", list);
		model.addAttribute("choiseRoles", choiseRoles);
		model.addAttribute("user", user);
		return "user/user_update";
	}
	
	/**
	 * 修改
	 * @param user
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("update")
	public String update(User user, String roles) {
		if (!StringUtils.isNullOrEmpty(user.getPassword())) {
			PasswordHelp.getNewPassword(user);	//如果密码不为空，表示用户想修改密码，则调用加密工具类进行修改密码
		}else {
			user.setPassword(null);
		}
		user.setUpdateUser(SessionUtils.getUserName());
		user.setStatus(user.getStatus()==null?-1:1);
		
		userMapper.updateByPrimaryKeySelective(user);
		
		//把用户角色关联表的信息更新
		//1、先删除用户角色关联表中相关的信息
		UserroleExample userroleExample = new UserroleExample();
		userroleExample.createCriteria().andUserIdEqualTo(user.getId());
		userroleMapper.deleteByExample(userroleExample);
		
		//2、再把勾选的角色信息保存到用户角色关联表中
		String[] roleArr = roles.split(",");
		for (String role : roleArr) {
			Userrole userrole = new Userrole();
			userrole.setRoleId(role);
			userrole.setUserId(user.getId());
			userroleMapper.insert(userrole);
		}
		return "";
	}
	
	/**
	 * 修改状态
	 * @param user
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("updateStatus")
	public String updateStatus(User user) throws IOException{
		userMapper.updateByPrimaryKeySelective(user);
		return "";
	}
}
